import 'package:campus_vision/models/player/player_count.dart';
import 'package:campus_vision/providers/video_player_count_provider.dart';
import 'package:campus_vision/providers/video_player_provider.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../models/device/channel.dart';
import 'device_providers.dart';

part 'multi_video_player_provider.g.dart';

class MultiVideoContext {
  final int? currentDeviceId;
  final List<PlayerCount> visiblePlayerCount;
  final List<int> currentChannelIds;
  final int? focusChannelId;
  const MultiVideoContext({
    this.currentDeviceId,
    this.visiblePlayerCount = PlayerCount.values,
    this.currentChannelIds = const [],
    this.focusChannelId,
  });

  MultiVideoContext copyWith({
    int? deviceId,
    PlayerCount? playerCount,
    List<PlayerCount>? visiblePlayerCount,
    List<int>? currentChannelIds,
    int? focusChannelId,
  }) {
    return MultiVideoContext(
      currentDeviceId: deviceId ?? currentDeviceId,
      visiblePlayerCount: visiblePlayerCount ?? this.visiblePlayerCount,
      currentChannelIds: currentChannelIds ?? this.currentChannelIds,
      focusChannelId: focusChannelId ?? this.focusChannelId,
    );
  }

  MultiVideoContext resetFocusChannel() {
    return copyWith(focusChannelId: null); // 👈 复用 copyWith，避免重复代码
  }
}

@riverpod
class MultiVideoPlayer extends _$MultiVideoPlayer {
  @override
  Future<MultiVideoContext> build() async {
    // 1. 初始化状态
    const initialContext = MultiVideoContext();

    // 2. 监听 playScreenCountProvider 的变化
    ref.listen(videoPlayerCountProvider, (previous, next) async {
      final currentContext = state.value;
      if (currentContext != null && previous != next) {
        state = await AsyncValue.guard(() async {
          final deviceId = state.value?.currentDeviceId;
          if (deviceId == null) throw Exception("deviceId is null");
          await _resetLast(deviceId);
          final channelList =
              await ref.watch(channelListProvider(deviceId).future);
          return state.value!.copyWith(
            currentChannelIds: _currentChannelIds(channelList, next),
          );
        });
      }
    });
    return initialContext;
  }

  Future<void> changedDevice(int deviceId) async {
    if (deviceId == state.value?.currentDeviceId) return;
    try {
      state = const AsyncValue.loading();
      final channelList = await ref.watch(channelListProvider(deviceId).future);
      final visiblePlayerCount = _dimensionsPlayerCount(channelList.length);
      final playerCount = ref.read(videoPlayerCountProvider);
      state = AsyncValue.data(
        state.value!.copyWith(
          deviceId: deviceId,
          visiblePlayerCount: visiblePlayerCount,
          currentChannelIds: _currentChannelIds(channelList, playerCount),
        ),
      );

      await ref.read(deviceDetailProvider(deviceId).future);
    } catch (e, st) {
      // 加载失败，保持原状态或记录错误
      state = AsyncValue.error(
        e,
        st,
      );
    }
  }

  Future<void> _resetLast(int deviceId) async {
    final channelIdList = state.value?.currentChannelIds ?? [];
    for (var channelId in channelIdList) {
      ref.invalidate(videoPlayerStateProvider(deviceId, channelId));
    }
  }

  List<int> _currentChannelIds(List<Channel> list, PlayerCount playerCount) {
    final maxCount = playerCount.maxVideoCount;
    final List<int> ids = [];
    for (var i = 0; i < list.length; i++) {
      if (i < maxCount) {
        ids.add(list[i].id!);
      } else {
        return ids;
      }
    }
    return ids;
  }

  List<PlayerCount> _dimensionsPlayerCount(int count) {
    if (count < 2) return [PlayerCount.single];
    if (count < 5) return [PlayerCount.single, PlayerCount.quad];
    if (count < 7) {
      return [PlayerCount.single, PlayerCount.quad, PlayerCount.six];
    }
    return PlayerCount.values;
  }
}
